<template>
  <div class="header">
    <el-header  >
      <div >
        <el-col :span="1" v-show="showIcon"  class="user-info"  style="left: 0px">
          <el-image
            style="width: 150px; height: 50px;left: 30px;margin-top: 5px"
            :src="url"></el-image>
        </el-col>
      </div>
      <div >
        <el-col :span="6"  class="user-info"  style="left: 300px">
          <ul style="list-style:none;color: #82848a;">
<!--            <li  class="li" @click=""><a href="https://gitee.com/yundongshenggzs/mybatis-plugs" style="text-decoration:none;color: #e4e8f1;padding: 8px"   target="_blank">代码地址</a></li>-->

<!--            <li  class="li" @click=""><a href="http://www.youandi.top:9880/#/" style="text-decoration:none;color: #e4e8f1;padding: 8px"   target="_blank">开发文档</a></li>-->

          </ul>
        </el-col>
      </div>


      <div class="icon-wrap">

        <el-col :span="3"  class="user-info" v-bind:style="styleName">
          <i v-bind:class="className"  id="i1" @click="_collapseChange"></i>
        </el-col>



        <el-col :span="2"  class="user-info"  style="right: 290px">
          <div >
            <el-badge :value="msgCount" class="item" >
              <p @click="msgLook"  style="font-size: 50%" >消息</p>
            </el-badge>
          </div>

        </el-col>


        <el-col :span="2"  class="user-info"  style="right: 190px">
          <span style="font-size: 12px;color: white"> 账户：{{userName}}</span>
        </el-col>


        <el-col :span="2"  class="user-info"  style="right:70px">
          <el-dropdown>
            <i  style="margin-right: 1px">
              <el-image
                style="width: 50px; height: 50px;margin-top: 5px;border-radius: 50%;"
                :src="this.imageUrl"></el-image>

            </i>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item  @click.native="_lookUserInfo">查看</el-dropdown-item>
              <el-dropdown-item @click.native="_loginOut">退出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </div>
      <el-dialog
        title="用户信息"
        :visible.sync="centerDialogVisible"
        width="30%"
        center>
        <el-upload style="text-align: center"
                   class="avatar-uploader"
                   :action="action"
                   :show-file-list="false"
                   :on-success="handleAvatarSuccess"
                   :with-credentials="true"
                   :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>


        <span>用户名：</span><span>{{userName}}</span><br/>
        <span>年龄：</span><span>{{userInfo.age}}</span><br/>
        <span>邮箱：</span><span>{{userInfo.mail}}</span><br/>
        <span>手机号：</span><span>{{userInfo.phone}}</span><br/>
        <span slot="footer" class="dialog-footer">
      <el-button @click="centerDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
  </span>
      </el-dialog>


    </el-header>

  </div>

</template>

<script>
export default {

  created() { // 页面创建生命周期函数
    // this.initWebSocket()
  },
  destroyed: function () { // 离开页面生命周期函数
    this.webSocketClose();
  },

  mounted(){

     this._getUserInfo();
    this._getMsgCount();
  },


  props:{
    showIcon:true,
  },

  data () {
    return {
      msg: 'mybatis-plugs',
      userName:'',
      isCollapse: false,
      imageUrl:'',
      className:'el-icon-s-fold',
      styleName:'left: 100px',
      businessId:'',
      headPic: 'static/mes.png',
      userInfo:'',
      action:'',
      centerDialogVisible:false,
      fits: [ 'contain', ],
      msgCount:0,
      url: 'static/mes.png'
    }
  },
  methods:{
    initWebSocket: function () {
      // // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      // console.log(localStorage.getItem('userInfo'))
      // console.log(localStorage.getItem('userInfo').id)
      // let userId = localStorage.getItem('userId')
      // this.websock = new WebSocket("ws://api.youandi.top:9888/websocket/"+userId);
      // this.websock.onopen = this.webSocketOnOpen;
      // this.websock.onerror = this.webSocketOnError;
      // this.websock.onmessage = this.webSocketOnMessage;
      // this.websock.onclose = this.webSocketClose;
    },

    webSocketOnOpen: function () {
      console.log("WebSocket连接成功");
    },
    webSocketOnError: function (e) {
      console.log("WebSocket连接发生错误",e);
    },
    webSocketOnMessage: function (e) {
      this._msgManage(e.data)
      this._getMsgCount()
    },
    webSocketClose: function (e) {
      console.log("connection closed (" + e + ")");
    },
    handleAvatarSuccess(res, file) {
     let  user = this._getUser()
      this.$http.get('/api/base/sys_user/preview?id='+user).then(res=>{
        this.imageUrl = res.data.data;
        localStorage.setItem('headerImageUrl', this.imageUrl)
      }).catch(err=>{
        console.log(err)
      })

    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },

    _msgManage(msg){
      if (msg!==null&&undefined!=msg&&''!=msg){
        this.$notify.info({
          title: '消息',
          message: msg
        });
      }

    },
    _getMsgCount(){
      this.$http.get('/api/base/sys_msg_rel_user/getMsgCount').then(res=>{
        let returnData=res.data
        if (undefined === returnData || '' ===returnData){
          this.$router.push({path:'/login',query:{}});
        }else{
          if (this._isNumber(returnData.data)){
            this.msgCount = returnData.data
          }
        }


      }).catch(err=>{
        console.log(err)
      })
    },

   _isNumber(val){

        let regPos = /^\d+(\.\d+)?$/; //非负浮点数
        let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
        if(regPos.test(val) || regNeg.test(val)){
          return true;
        }else{
          return false;
        }
   },
    _getUser(){
      return   localStorage.getItem('userId')
    },

    _getUserInfo(){

    let userInfo=  localStorage.getItem('userInfo')
      console.log('-----------------user',userInfo)
      if (null === userInfo || undefined === userInfo){
        this.$router.push({path:'/login',query:{}});
      }else{
        this.$router.push({path:'/',query:{}});
        this.action = localStorage.getItem('action')
        this.imageUrl = localStorage.getItem('headerImageUrl')
        this.userName = localStorage.getItem('userName')
        if (undefined!==localStorage.getItem('msgCount')&&null!=localStorage.getItem('msgCount')){
          this.msgCount = localStorage.getItem('msgCount');
        }
      }
    },



    _collapseChange(){
      if (this.isCollapse) {
        this.isCollapse=false;
        this.className='el-icon-s-fold',
        this.styleName='left: 100px'
      }else{
        this.isCollapse=true;
        this.className='el-icon-s-unfold',
        this.styleName='left: -60px'
      }

      this.$emit("on-result-change",this.isCollapse);
    },

    _lookUserInfo(){
     this. centerDialogVisible=true;
    },
    msgLook(){

      this.$router.push({path:'/msg/my_msg',query:{}});

    },

    _loginOut(){

      this.$confirm('是否退出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        localStorage.clear()
        this.$http.post('/api/base/auth/logout').then(res=>{
          this.$router.push({path:'/login',query:{}});
        }).catch(err=>{
          this.$router.push({path:'/login',query:{}});
          console.log(err)
        })
      }).catch(() => {

      });
    },
  },
}
</script>

<style scoped>
  .header {
    flex: 1;
    display: flex;
    flex-direction: column;
    width: auto;
    height: 60px;
    line-height: 60px;
    background: #72767b;
    color: #fff;
  }
  .header-logo{
    height: 60px;
    float: left;
    margin: 0 20px;
    width: 100%;
  }
  .user-info{
    position: absolute;
    right: 0;
  }

  .icon-wrap{
    margin-left: 100px;
    width: 100px;
    height: 100px;
    font-size: 30px;
  }


  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .li{
    float: left;
    margin-left: 10px;
  }

  /*li:hover*/
  /*{*/
  /*  background: #333;*/
  /*}*/

  li:nth-child(1) {
    background: red;
  }

  .item {
    margin-top: 12px;
    margin-right: 0px;
  }



</style>
